import os.path

import requests
import re
import zipfile
from tqdm import tqdm
ac_id = input('请你输入你要下载的视频ID：')
url = f'https://www.acfun.cn/v/{ac_id}'

headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}

resp = requests.get(url,headers=headers)
#print(resp.text)
#获取视频的标题
title = re.findall('<h1 class="title"><span>(.*?)</span>',resp.text)[0]
print(title)

#获取m3u8 url地址
m3u8_url = re.findall('backupUrl(.*?)\"]',resp.text)[0].replace('"','').split('\\')[2]
#print(m3u8_url)
#获取m3u8的数据
m3u8_data = requests.get(url=m3u8_url,headers=headers).text

m3u8_data = re.sub('#EXTM3U','',m3u8_data)
m3u8_data = re.sub('#EXT-X-VERSION:\d','',m3u8_data)
m3u8_data = re.sub('#EXT-X-TARGETDURATION:\d+','',m3u8_data)
m3u8_data = re.sub('#EXT-X-MEDIA-SEQUENCE:\d','',m3u8_data)
m3u8_data = re.sub('#EXTINF:\d\.\d+,','',m3u8_data)
m3u8_data = re.sub('#EXT-X-ENDLIST','',m3u8_data)
#print(m3u8_data)
m3u8_data_list = m3u8_data.split()
#print(m3u8_data_list)

#下载ts文件
pre_url = 'https://tx-safety-video.acfun.cn/mediacloud/acfun/acfun_video/'
filename = f'{title}\\'
if not os.path.exists(filename):
    os.mkdir(filename)
print("正在开始下载ts文件，请稍后......")
for item in tqdm(m3u8_data_list):
    link_url = pre_url + item
    link_name = item.split('.')[1]
    link_content = requests.get(url=link_url,headers=headers).content

    with open(filename + link_name + '.ts',mode='wb') as f:
        f.write(link_content)
print("ts 视频下载完成！")

print("开始视频片段合成.....")
files =os.listdir(filename)
#print(files)
with zipfile.ZipFile(filename + title + '李鸿' + '.mp4',mode='w') as z:
    for file in tqdm(files):
        ts_conten = filename + file
        z.write(ts_conten)
        os.remove(ts_conten)

print("视频片段合成完成！")